package com.lmind.core.publish;

import java.util.ArrayList;

import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Test;

public class SimplePublisherRouterTestCase {
	
	@BeforeClass
	public static void beforeClass() throws Exception {
		
	}

	@Test
	public void test() throws Exception {
		
		String news = "New York Times";
		SimplePublisher<Object> pub = new SimplePublisher<Object>();		

		SimplePublisherRouter<Object> router = new SimplePublisherRouter<Object>();
		router.setPublisher(pub);
		
		ArrayList<MySubscriber> subs = new ArrayList<MySubscriber>();
		for (int i = 0; i < 10; i++) {
			MySubscriber sub = new MySubscriber();
			subs.add(sub);
			router.subscribe(sub, news);
		}
		Assert.assertEquals(pub.getSubscribeCount(), 1);
		
		pub.publish(news, "The World War");
		for (MySubscriber sub : subs) {
			Assert.assertTrue(sub.lastPublication.equals("The World War"));
		}
		
		
		for (int i = 0; i < 9; i++) {
			router.unsubscribe(subs.remove(0), news);
		}
		Assert.assertEquals(pub.getSubscribeCount(), 1);
		pub.publish(news, "The World War");
		for (MySubscriber sub : subs) {
			Assert.assertTrue(sub.lastPublication.equals("The World War"));
		}
		
		router.unsubscribe(subs.remove(0), news);
		Assert.assertEquals(pub.getSubscribeCount(), 0);
		
	}
	
	@Test
	public void testCleanSubscribe() throws Exception {
		
		String news = "New York Times";
		SimplePublisher<Object> pub = new SimplePublisher<Object>();		

		SimplePublisherRouter<Object> router = new SimplePublisherRouter<Object>();
		router.setPublisher(pub);
		
		MySubscriber sub = new MySubscriber();
		for (int i = 0; i < 10; i++) {
			router.subscribe(sub, news + "_" + i);
		}
		Assert.assertEquals(pub.getSubscribeCount(), 10);
		
		router.cleanSubscribe(sub);
		Assert.assertEquals(pub.getSubscribeCount(), 0);
	}
	
	public static class MySubscriber implements Subscriber<Object> {
		
		public String lastName;
		
		public Object lastPublication;
		
		@Override
		public void feed(String name, Object publication) {
			lastName = name;
			this.lastPublication = publication;
		}
	}
	
	

}
